package com.coffee_shop_app.module.http;

import android.content.Context;
import android.os.Environment;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.coffee_shop_app.common.BaseException;
import com.coffee_shop_app.common.ObjectRestResponse;
import com.coffee_shop_app.database.dao.PcrData;
import com.coffee_shop_app.service.EmbeddedService;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import fi.iki.elonen.NanoHTTPD;

/**
 * http 框架
 */
public class MyNanoHttpdServer extends NanoHTTPD {

    private static Context selfCcontext = null;

    //声明服务端 端口
    private static final Integer HTTP_PORT = 49152;

    private static final  String webRoot = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/com.coffee_shop_app/files/";

    public MyNanoHttpdServer(String hostname, int port) {
        super(port);
    }

    private volatile static MyNanoHttpdServer myNanoHttpdServer;
    /**
     * 处理设备文件数据
     */
    private volatile static EmbeddedService embeddedService;

    //TODO	单例模式，获取实例对象，并传入当前机器IP
    public static MyNanoHttpdServer getInstance(String ipAddress, Context context) {
        if (myNanoHttpdServer == null) {
            synchronized (MyNanoHttpdServer.class) {
                if (myNanoHttpdServer == null) {
                    myNanoHttpdServer = new MyNanoHttpdServer(ipAddress, HTTP_PORT);
                    embeddedService = new EmbeddedService(context);
                    selfCcontext = context;
                }
            }
        }
        return myNanoHttpdServer;
    }

    @Override
    public Response serve(IHTTPSession session) {
        //TODO  解决客户端请求参数携带中文，出现中文乱码问题
        ContentType ct = new ContentType(session.getHeaders().get("content-type")).tryUTF8();
        session.getHeaders().put("content-type", ct.getContentTypeHeader());
        return dealWith(session);
    }

    /**
     * 业务层面
     * @param session
     * @return
     */
    private Response dealWith(IHTTPSession  session) {
        Date dateTime = new Date();
        Log.i("UI", session.getMethod().toString());
        if (Method.POST == session.getMethod()) {
            //获取请求头数据
            Map<String, String> header = session.getHeaders();
            //获取传参参数
            Map<String, String> params = new HashMap<String, String>();
            try {
                session.parseBody(params);
                Map<String, List<String>> parameters = session.getParameters();
                /**
                 * 处理设备文件
                 */
                embeddedService.checkFileAndSave(params, parameters, session.getRemoteHostName());
                return newFixedLengthSuccessResponse("传输成功");
//                //TODO 写你的业务逻辑.....
//                Log.i("result", paramStr);
            } catch (BaseException e) {
                e.printStackTrace();
                return newFixedLengthBidResponse(e.getMessage(), e.getCode());
            } catch (Exception e) {
                e.printStackTrace();
                return newFixedLengthBidResponse(e.getMessage(), -2);
            }
        } else if (Method.GET == session.getMethod()) {
            String uri = session.getUri();
            //获取传参参数
            Map<String, String> params = new HashMap<String, String>();
            Map<String, List<String>> parameters = session.getParameters();
            /**
             * 获取静态资源
             */
            if (uri.indexOf("/static") > -1) {
                File file = new File(webRoot, uri.substring(uri.indexOf("/static") + 7));
                if (file.exists()) {
                    if (file.isFile()) {
                        return render200(uri, file);
                    } else {
                        if (uri.endsWith("/")) {
                            File indexFile = new File(file, "index.html");
                            if (indexFile.exists()) {
                                return render200(uri + "index.html", indexFile);
                            } else {
                                return render404();
                            }
                        } else {
                            return render301(uri + "/");
                        }
                    }
                } else {
                    return render404();
                }
            }

            /**
             *  设备数据list 列表
             */
             if (uri.indexOf("/pcrdata/list") > -1) {
                 List<PcrData>  pcrDataList =  embeddedService.getPcrDataList();
                 return newFixedLengthSuccessResponse("获取所有实验列表成功", pcrDataList);
             }

            /**
             *  设备数据id 查询数据
             */
            if (uri.indexOf("/pcrdataById") > -1) {
                List<String> paramIdList = parameters.get("id");
                String id = paramIdList.get(0).replace("\r\n", " ");
                PcrData selectPcrData = embeddedService.getPcrDataById(id);
                return newFixedLengthSuccessResponse("设备数据id 查询数据成功", selectPcrData);
            }

            /**
             *  检测项目查询
             */
            if (uri.indexOf("/selectPcrdata") > -1) {
                List<String> paramChipnameCNList = parameters.get("chipnameCN");
                if (paramChipnameCNList != null) {
                    String chipnameCN = paramChipnameCNList.get(0).replace("\r\n", " ");
                    List<PcrData> pcrDataList = embeddedService.getPcrDataByChipnameCN(chipnameCN);
                    return newFixedLengthSuccessResponse("通过检测项目查询实验信息成功", pcrDataList);
                }
                /**
                 *  检测样品信息
                 */
                List<String> paramSampleNoList = parameters.get("sampleNo");
                if (paramSampleNoList != null) {
                    String sampleNo = paramSampleNoList.get(0).replace("\r\n", " ");
                    List<PcrData> pcrDataList = embeddedService.getPcrDataBySampleNo(sampleNo);
                    return newFixedLengthSuccessResponse("通过检测样品信息获取实验记录成功", pcrDataList);
                }

                /**
                 *  检测时间
                 */
                List<String> paramStartTimeList = parameters.get("startTime");
                if (paramStartTimeList != null) {
                    String startTime = paramStartTimeList.get(0).replace("\r\n", " ");
                    List<PcrData> pcrDataList = embeddedService.getPcrDataByStartTime(Long.valueOf(startTime));
                    return newFixedLengthSuccessResponse("通过检测样品获取实验信息成功", pcrDataList);
                }
            }
        }
        return newFixedLengthSuccessResponse("传输成功");
    }

    /**
     * 成功响应
     * @param msg
     * @return
     */
    public static Response newFixedLengthSuccessResponse(String msg,  Object result) {
        msg = JSON.toJSONString(new ObjectRestResponse<>().msg(msg).rel(com.coffee_shop_app.common.Response.SUCCESS).result(result));
        return newFixedLengthResponse(Response.Status.OK, NanoHTTPD.MIME_HTML, msg);
    }

    /**
     * 成功响应
     * @param msg
     * @return
     */
    public static Response newFixedLengthSuccessResponse(String msg) {
        msg = JSON.toJSONString(new ObjectRestResponse<>().msg(msg).rel(com.coffee_shop_app.common.Response.SUCCESS));
        return newFixedLengthResponse(Response.Status.OK, NanoHTTPD.MIME_HTML, msg);
    }

    /**
     * 失败响应
     * @param msg
     * @return
     */
    public static Response newFixedLengthBidResponse(String msg, Integer code) {
        msg = JSON.toJSONString(new ObjectRestResponse<>().msg(msg).rel(com.coffee_shop_app.common.Response.FAILURE).code(code));
        return newFixedLengthResponse(Response.Status.BAD_REQUEST, NanoHTTPD.MIME_HTML, msg);
    }

    /**
     * 失败响应
     * @param msg
     * @return
     */
    public static Response newFixedLengthBidResponse(String msg) {
        msg = JSON.toJSONString(new ObjectRestResponse<>().msg(msg).rel(com.coffee_shop_app.common.Response.FAILURE));
        return newFixedLengthResponse(Response.Status.BAD_REQUEST, NanoHTTPD.MIME_HTML, msg);
    }

    /**
     *  静态传输文件
     * @param uri
     * @param file
     * @return
     */
    private Response render200(String uri, File file) {
        try {
            return NanoHTTPD.newFixedLengthResponse(NanoHTTPD.Response.Status.OK, NanoHTTPD.getMimeTypeForFile(uri), new FileInputStream(file), file.length());
        } catch (FileNotFoundException e) {
            return render500(e.getMessage());
        }
    }

    private Response render500(String text) {
        return NanoHTTPD.newFixedLengthResponse(NanoHTTPD.Response.Status.INTERNAL_ERROR, NanoHTTPD.MIME_PLAINTEXT, text);
    }

    private Response render404() {
        File file = new File(webRoot, "404.html");
        if (file.exists()) {
            try {
                return NanoHTTPD.newFixedLengthResponse(NanoHTTPD.Response.Status.NOT_FOUND, NanoHTTPD.MIME_HTML, new FileInputStream(file), file.length());
            } catch (FileNotFoundException e) {
                return render500(e.getMessage());
            }
        } else {
            return NanoHTTPD.newFixedLengthResponse(NanoHTTPD.Response.Status.NOT_FOUND, NanoHTTPD.MIME_HTML, null);
        }
    }

    private Response render301(String next) {
        Response res = newFixedLengthResponse(Response.Status.REDIRECT, NanoHTTPD.MIME_HTML, null);
        res.addHeader("Location", next);
        return res;
    }

}